const mysql   = require('mysql2/promise')
const { env } = require('../config')
const { DbError } = require('../error')

let clusterConfig = {
  removeNodeErrorCount: 1, // Remove the node immediately when connection fails.
  defaultSelector: 'RR',
};

let pool = mysql.createPoolCluster(clusterConfig);
// More instances can be added
pool.add('MASTER', {
  host: env.MYSQL.HOST,
  user: env.MYSQL.USER,
  password: env.MYSQL.PASS,
  database: env.MYSQL.DB,
  connectionLimit: env.MYSQL.LIMIT || 5,
});
pool.add('SLAVE', {
  host: env.MYSQL_SLAVE.HOST,
  user: env.MYSQL_SLAVE.USER,
  password: env.MYSQL_SLAVE.PASS,
  database: env.MYSQL_SLAVE.DB,
  connectionLimit: env.MYSQL_SLAVE.LIMIT || 5,
});

// 好像无效
pool.on('remove', function (nodeId) {
  console.info('==== REMOVED NODE : ' + nodeId);
});
pool.on('connection', function (stream) {
  console.log('==== conn %d connected', stream);
  // conn.query('SET SESSION auto_increment_increment=1')
});

let masterPool = pool.of('MASTER', 'RR');
let slavePool  = pool.of('SLAVE', 'RR');

exports.getConn = async (trans = false) => {
  const conn = await masterPool.getConnection()
  // let err
  // [err,conn] = await awaits(pool.getConnection())
  //   Error{name,message,stack,errno,code,syscall,address,port,fatal} null
  //   null Mysql.PoolConnection
  //   console.log('getconn ',typeof err ,'==', conn)
  if (trans) await conn.beginTransaction()
  // 后面请自行调用
  // conn.rollback()
  // conn.commit()
  return conn
}

exports.getConns = async (trans = false) => {
  let conn
  try {
    conn = await masterPool.getConnection(multi)
    if (trans) await conn.beginTransaction()
  } catch (e) {
    if (e.errno) {
      throw new DbError(e.code, e.errno)
    } else {
      throw e
    }
  }
  return conn
}

exports.getConnSlave = async (trans = false) => {
  let conn
  try {
    conn = await slavePool.getConnection()
    if (trans) await conn.beginTransaction()
  } catch (e) {
    if (e.errno) {
      throw new DbError(e.code, e.errno)
    } else {
      throw e
    }
  }
  return conn
}

exports.getConnsSlave = async (trans = false) => {
  let conn
  try {
    conn = await slavePool.getConnection(multi)
    if (trans) await conn.beginTransaction()
  } catch (e) {
    if (e.errno) {
      throw new DbError(e.code, e.errno)
    } else {
      throw e
    }
  }
  return conn
}

// masterPool.getConnection(function (err, connection) {
//   if (err) {
//     logger.error(err.message);
//   } else {
//     logger.info('Database connected masterPool successfully');
//   }
// });
// slavePool.getConnection(function (err, connection) {
//   if (err) {
//     logger.error(err.message);
//   } else {
//     logger.info('Database connected slavePool successfully');
//   }
// });
